package xiaopiya.robot.handler.help;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

/**
 * 获得Help的配置数据
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class HelpConfigFactoryBean implements FactoryBean, InitializingBean
{
	private final static Log LOG = LogFactory.getLog(HelpConfigFactoryBean.class);
	
	private HelpConfig helpConfig = new HelpConfig();

	private Resource helpConfigResource;

	public void setHelpConfigResource(Resource helpConfigResource)
	{
		this.helpConfigResource = helpConfigResource;
	}

	public void afterPropertiesSet() throws Exception
	{
		if (this.helpConfigResource == null)
		{
			throw new IllegalArgumentException(
					"helpConfigResource can't be null");
		}
		
		if (LOG.isInfoEnabled())
		{
			LOG.info("Load help content");
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		IOUtils.copy(this.helpConfigResource.getInputStream(), baos);

		Document document = DocumentHelper.parseText(new String(baos
				.toByteArray()));
		Element root = document.getRootElement();
		root.accept(new VisitorSupport()
		{
			public void visit(Element node)
			{
				if ("param".equals(node.getName()))
				{
					String names = node.attributeValue("name");
					String[] array = names.split("\\|");
					String contentFileName = node.attributeValue("content");
					String content = readHelpContent(contentFileName);
					for (String name : array)
					{
						name = name.trim();
						helpConfig.add(name, content);
						if (LOG.isInfoEnabled())
						{
							LOG.info("load help content for command [" + name + "]");
						}
					}
				}
			}

			private String readHelpContent(String contentFileName)
			{
				String path = "/config/module/help/" + contentFileName;
				InputStream contentStream = HelpConfigFactoryBean.class
						.getResourceAsStream(path);
				if (contentStream == null)
				{
					throw new IllegalStateException(
							"Can't find content from path[" + path + "]");
				}
				ByteArrayOutputStream content = new ByteArrayOutputStream();
				try
				{
					IOUtils.copy(contentStream, content);
				} catch (IOException e)
				{
					throw new IllegalStateException(
							"error when read help txt[" + path + "]", e);
				}
				String result = null;
				try
				{
					result = new String(content.toByteArray(), "utf-8");
				} catch (UnsupportedEncodingException e)
				{
					result = new String(content.toByteArray());
				}
				if (LOG.isInfoEnabled())
				{
					LOG.info("load help[" + result + "] from [" + path + "]");
				}
				return result;
			}
		});
		
		if (LOG.isInfoEnabled())
		{
			LOG.info("Load help content success!");
		}
	}

	public Class getObjectType()
	{
		return HelpConfig.class;
	}

	public Object getObject() throws Exception
	{
		return this.helpConfig;
	}

	public boolean isSingleton()
	{
		return true;
	}
}
